import json
from typing import List

import requests
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from langchain_core.tools import tool

from core.base import milvus_vector_store
from util.SearxngUtil import search_searxng

@tool
def get_weather(location):
    """根据城市获取天气数据"""
    api_key = "SKcA5FGgmLvN7faJi"
    url = f"https://api.seniverse.com/v3/weather/now.json?key={api_key}&location={location}&language=zh-Hans&unit=c"
    response = requests.get(url)
    print(response)
    if response.status_code == 200:
        data = response.json()
        # print(data)
        weather = {
            'description': data['results'][0]["now"]["text"],
            'temperature': data['results'][0]["now"]["temperature"]
        }
        return weather
    else:
        raise Exception(f"失败接收天气信息：{response.status_code}")

@tool
def searxng_search(query):
    """输入搜索内容，使用 SearXNG 进行搜索。"""
    SEARXNG_URL = 'http://172.20.0.116:8080/'

    # 发送 GET 请求
    response =search_searxng(SEARXNG_URL, query, 3)
    print(response.text)
    # return response.text
    # 检查响应状态码
    if response.status_code == 200:
        res = response.json()
        # print(res)
        resList = []
        for item in res['results']:
            resList.append({
                "title": item['title'],
                "content": item['content'],
                "url": item['url']
            })
            if len(resList) >= 3:
                break
        return resList
    else:
        return response.raise_for_status()

# print(searxng_search.invoke("郭德纲"))

@tool
def milvus_search(query):
    """从企业知识库检索航空、专业信息"""
    # 初始化  向量数据库
    vector_store = milvus_vector_store()
    # 初始化检索，并配置
    retriever = vector_store.as_retriever(
        search_type="similarity",
        search_kwargs={
            "k": 5,  # 检索结果返回最相似的文档数量
            # "fetch_k": 20,  # 要传递给 MMR 算法的文档量
            # "search_type": "mmr",
            "score_threshold": 0.7,  # 相似度阈值过滤
             "ranker_type": "weighted",
            "ranker_params": {"weights": [0.6, 0.4]}
        }
    )
    return  docs_to_dict(retriever.invoke(query))
def docs_to_dict(docs: List[Document]) -> List[dict]:
    """将Document列表转为结构化字典"""
    return [
        {
            "text": doc.page_content,
            "source": doc.metadata.get("source"),
            "score": doc.metadata.get("score", 0.0)  # 兼容带评分的检索器
        }
        for doc in docs
    ]

# milvus_search.invoke("航空汽油")


from langchain_community.utilities import SearxSearchWrapper
search = SearxSearchWrapper(searx_host="http://172.20.0.116:8080/")
result = search.run("刘亦菲近况")

results = search.results(
    query="刘亦菲近况",
    num_results=5,  # 返回结果数量
    engines=["baidu","360search","sogou"],
    language="zh-CN"  # 可选：指定语言为中文
)
print(results)